package service.impl;

import mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import entity.SysUser;
import service.SysUserService;
import utils.Page;


import java.util.List;
@Service("sysUserService")

public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public List<SysUser> getUserList(SysUser user) {
        return sysUserMapper.getUserList(user);
    }

    @Override
    @Transactional
    public int saveBatch(List<SysUser> list) {
        int rows=0;
        for (int i = 0; i < list.size(); i++) {
            SysUser user = list.get(i);
            if(i==1){
                throw new RuntimeException("数据库异常");
            }
            rows += sysUserMapper.insert(user);
        }
        return rows;
    }

    @Override
    @Transactional
    public int add(SysUser user) {
        return sysUserMapper.insert(user);
    }

    @Override
    @Transactional
    public boolean update(SysUser sysUser) {
        return sysUserMapper.update(sysUser)>0;
    }

    @Override
    @Transactional
    public int delete(Integer id) {
        return sysUserMapper.delete(id);
    }

    @Override
    public SysUser login(String account, String password) {
        SysUser sysUser = sysUserMapper.getByAccount(account);
        //匹配密码
        if (null != sysUser) {
            if (sysUser.getPassword().equals(password))
                return sysUser;
        }
        return null;
    }

    @Override
    public Page<SysUser> findPage(SysUser sysUser, Integer pageNo, Integer pageSize) {
        Page<SysUser> page = new Page<SysUser>();
        page.setPageSize(pageSize);
        // 查询总数，计算总页数
        Integer count = sysUserMapper.count(sysUser);
        page.setTotalCount(count);
        page.setPageNo(pageNo);
        // 查询分页数据
        Integer pageBegin=(pageNo-1)*pageSize;
        List<SysUser> data = sysUserMapper.getPage(sysUser, page.offset(), page.getPageSize());
        page.setData(data);
        return page;
    }

    @Override
    public boolean save(SysUser sysUser) {
        return sysUserMapper.insert(sysUser) > 0;
    }

    @Override
    public SysUser findById(Long id) {
        return sysUserMapper.getById(id);
    }

    @Override
    public SysUser findByAccount(String account) {
        return sysUserMapper.getByAccount(account);
    }

    @Override
    public SysUser getByPassword(String password) {
        return sysUserMapper.getByPassword(password);
    }
}
